﻿using Inovout.Component;
using Inovout.Data.Service;
using Inovout.People.Domain;
using Inovout.People.Membership.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Inovout.Cloud.Messager.WebPage.Models
{
    public class PersonMembershipLogic : RepositoryService<PersonMembership>
    {

        PersonLogic personlogic = new PersonLogic();
        IRepositoryService<PersonMembership> Service = ComponentRegistry.Resolve<IRepositoryService<PersonMembership>>();
        public void HandlePersonMembership()
        {
            List<Person> persons = personlogic.GetAllPerson();
            List<PersonMembership> ships = GetPersonMembership();
            foreach (Person person in persons)
            {
                if (ships.Count()==0)
                {
                    PersonMembership ship = new PersonMembership();
                    ship.Person = person;
                    ship.Name = person.Name;
                    InsertPersonMembership(ship);
                }
                else
                {
                    //PersonMembership ship = ships.Where(c => c.Person == person).Select(c => c).SingleOrDefault();
                    PersonMembership ship = ships.Where(c => c.Name == person.Name).Select(c => c).SingleOrDefault();
                    if (ship == null)
                    {
                        PersonMembership shipd = new PersonMembership();
                        shipd.Person = person;
                        shipd.Name = person.Name;
                        InsertPersonMembership(shipd);
                    }
                    else
                    {
                        ships.Remove(ship);
                        ship.Person = person;
                        ship.Name = person.Name;
                        InsertPersonMembership(ship);
                    }
                }
            }
            RemovePersonMenbership(ships);
        }
        public void InsertPersonMembership(PersonMembership ship)
        {
            Service.Save(ship);
        }
        public void RemovePersonMenbership(List<PersonMembership> ships)
        {
            foreach (PersonMembership ship in ships)
            {
                Service.Delete(ship);
                MembershipUserLogic logic = new MembershipUserLogic();
                logic.RemoveMenbershipUser(ship);
            }
        }
        public List<PersonMembership> GetPersonMembership()
        {
            return Service.Query().ToList();
        }
    }
}